package com.xiangwei.util.zxing;

import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Binarizer;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

/**
 * zxing二维码生产工厂
 * 
 * @author yancy
 *
 */
public class QrcodeFactory {

	private static Integer number = 10000;      //每一个线程生成多少二维码
	/**
	 * 生成带二维码（logo可选，当logoPath为null时即不产生）
	 * 
	 * @param config
	 *            二维码参数对象（size color）
	 * @param num
	 *            生产数量
	 * @param imgPath
	 *            二维码存储路径
	 * @param content
	 *            二维码内容
	 * @param is
	 *            logo图片路径
	 * @param logoConfig
	 *            logo参数对象
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static void createQrcodes(QrcodeConfig config, String imgPath, String content, InputStream is,
			LogoConfig logoConfig) {
		/**
		 * 设置二维码的参数
		 */
		HashMap hints = new HashMap();
		// 内容所使用编码
		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
		// 设置QR二维码的纠错级别（H为最高级别）具体级别信息
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
		hints.put(EncodeHintType.MARGIN, config.getMargin());

		try {
			BitMatrix bitMatrix = null;
			// 生成二维码
			File outputFile = new File(imgPath);
			bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE,
					config.getWidth(), config.getHeight(), hints);
			MatrixToImageWriter.writeToFile(bitMatrix, config.getFormat(),
					outputFile, config.getColor(), config.getBgColor(),
					is, logoConfig);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	
	public static void createCodesFromTxt(String txtPath, String filePath,QrcodeConfig config,
			InputStream is,LogoConfig logoConfig) {
		String result = "";
		try {
			BufferedReader br = new BufferedReader(new FileReader(txtPath));// 构造一个BufferedReader类来读取文件
			String s = null;
			String url = "";
			String code="";
			int i = 1;
			while ((s = br.readLine()) != null) {// 使用readLine方法，一次读一行
				i++;
				String[] ss = s.split(",");
				if(ss.length>1){
					url = ss[0];
					code = ss[1];
					String realPath = filePath +"\\"+code + ".png";
					createQrcodes(config, realPath, url, is, logoConfig);
				}
			}
			br.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	
	
	
	
	/**
	 * 二维码的解析
	 * 
	 * @param file
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void parseCode(File file) {
		try {
			MultiFormatReader formatReader = new MultiFormatReader();

			if (!file.exists()) {
				return;
			}

			BufferedImage image = ImageIO.read(file);

			LuminanceSource source = new BufferedImageLuminanceSource(image);
			Binarizer binarizer = new HybridBinarizer(source);
			BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);

			Map hints = new HashMap();
			hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

			Result result = formatReader.decode(binaryBitmap, hints);

			System.out.println("解析结果 = " + result.toString());
			System.out.println("二维码格式类型 = " + result.getBarcodeFormat());
			System.out.println("二维码文本内容 = " + result.getText());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		System.out.println("主线程开始执行.....");
		// 二维码参数对象
		QrcodeConfig config = new QrcodeConfig();
		config.setColor(0xFF6699);
		config.setHeight(200);
		config.setWidth(200);

		// logo参数对象
		LogoConfig logoConfig = new LogoConfig();
		// logo文件
		// String logoPath = "F://qrcode3//logo.jpg";

		long startTime = System.currentTimeMillis();
		ExecutorService executorService = Executors.newFixedThreadPool(30);

		for (int i = 0; i < 5; i++) {
			executorService.execute(new Thread(new Runnable() {
				public void run() {
					String tname = Thread.currentThread().getName();
					System.out.println("------" + tname + "开始执行...");
					QrcodeFactory.createQrcodes(config, "F://qrcode2",
							"http://http://www.newxiangwei.com/xwtest/index.jsp?num=", null, logoConfig);
					System.out.println("******" + tname + "执行完毕...");

				}
			}));
		}
		executorService.shutdown();

		try {
			boolean loop = true;
			do { // 等待所有任务完成
				loop = !executorService.awaitTermination(2, TimeUnit.SECONDS);
			} while (loop);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		// 获取结束时间
		long endTime = System.currentTimeMillis();

		System.out.println("主线程执行完毕.....");
		System.out.println();

		// 输出程序运行时间
		System.out.println("程序运行时间：" + (endTime - startTime) + "ms");
	}
	
	
	/**
	 * 生成二维码
	 * @param map
	 */
	public static Boolean createQRCode(Map map) {
		// 二维码参数对象
		
		String color = map.get("color").toString();
		QrcodeConfig config = new QrcodeConfig();
		config.setColor(Integer.parseInt(color.substring(1),16));
		config.setHeight(Integer.valueOf(map.get("height").toString()));
		config.setWidth(Integer.valueOf(map.get("width").toString()));

		// logo参数对象
		LogoConfig logoConfig = new LogoConfig();
		ExecutorService executorService = Executors.newFixedThreadPool(30);

		Integer circle = 0;         //循环次数
		Integer all = Integer.parseInt(map.get("number").toString());     //总共生成多少个二维码
		
		circle = all/number;
		if(all%number!=0){
			circle++;
		}
		for (int i = 0; i < circle; i++) {
			if(i==circle-1&&all%number!=0){       //最后一次循环时候，如果总数除以每次生成的数量有余数，就生成该余数的数量
				number = all%number;
			}
			executorService.execute(new Thread(new Runnable() {
				public void run() {
					String tname = Thread.currentThread().getName();
					System.out.println(tname+"----");
					QrcodeFactory.createQrcodes(config,map.get("address").toString(),"百度一下，你就知道", null, logoConfig);
				}
			}));
		}
		executorService.shutdown();

		try {
			boolean loop = true;
			do { // 等待所有任务完成
				loop = !executorService.awaitTermination(2, TimeUnit.SECONDS);
			} while (loop);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		Boolean bool = true;
		return bool;
	}
}
